from django.contrib.admin import ModelAdmin, StackedInline

from app.models import ProductDetailImage, ProductSpec, Product


class ProductDetailImageInline(StackedInline):
    model = ProductDetailImage
    extra = 0


class ProductSpecInline(StackedInline):
    model = ProductSpec
    extra = 0


class ProductAdmin(ModelAdmin):
    list_display = ('id', 'name', 'category', 'description', '图片', 'is_on_shell')
    list_filter = ('category',)
    list_editable = ('is_on_shell',)
    inlines = (ProductDetailImageInline, ProductSpecInline)
    search_fields = ('name', 'description')

    def save_model(self, request, obj: Product, form, change):
        obj.save()
        for spec in obj.specs.all():
            spec.is_on_shell=obj.is_on_shell
            spec.save()



class ProductSpecAdmin(ModelAdmin):
    list_display = ('id', 'product', 'name', 'price', 'unit',
                    'price_for_display', 'discount', 'deposit', 'deposit_desc',
                    'stock', '图片', 'is_on_shell')
    list_filter = ('product__category', 'product')
    list_editable = ('price', 'stock', 'discount', 'is_on_shell', 'price_for_display')
    search_fields = ('name', 'product__name')


class ProductDetailImageAdmin(ModelAdmin):
    list_display = ('product', '图片')
